package com.huaqin.obeacons.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.content.Context;
import android.util.Log;
import cn.bmob.v3.listener.SaveListener;

import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import com.activeandroid.query.Update;
import com.huaqin.obeacons.R;
import com.huaqin.obeacons.bmob.SignInData;
import com.huaqin.obeacons.data.ShuaKaData;
import com.huaqin.obeacons.data.YouMengNews;

/**
 * @author xiabing 数据库工具类
 */
public class MyDatabaseUtil {
	// private static final String DB_CREATE =
	// "create table ibeacon_datatable(_id integer primary key autoincrement , date , time ,detail) ";
	// private static final String DB_NAME = "ibeacon_data.db";
	// private static final String DB_TABLE = "ibeacon_datatable";
	// private static MyDatabaseHelper databaseHelper;
	private static MyDatabaseUtil myDatabaseUtil;
	private List<DataListener> dataListeners;
	// private static final String DB_CREATE2 =
	// "create table obeacon_news(_id integer primary key autoincrement,title,content,time,type)";
	// private static final String DB_TABLE1 = "obeacon_news";
	private static Context contexts;
	private final static String TAG = "MyDatabaseUtil";

	private MyDatabaseUtil() {
	}

	public interface DataListener {
		void notifyDataUpdate();
	}

	public void addDataListener(DataListener dataListener) {
		if (dataListeners == null)
			dataListeners = new ArrayList<MyDatabaseUtil.DataListener>();
		dataListeners.add(dataListener);
	}

	public interface NotifyListener {
		void nofityMessageListShow();
	}

	private NotifyListener notifyListener;

	public void setNotifyListener(NotifyListener listener) {
		notifyListener = listener;
	}

	public static void insertDateTimeHelp(Context context) {
		Date now = new Date();
		insertDateTimeExtra(context, now);
	}

	public static void insertDateTimeHelpExtra(Context context, Date now) {
		insertDateTimeExtra(context, now);
	}

	// 插入 友盟消息推送数据 xiabing
	public static void insertDataFromumeng(Context context, String title,
			String content) {
		insertDataExtra(context, title, content);
	}

	// 插入 友盟消息推送数据 xiabing
	private static void insertDataExtra(Context context, String title,
			String content) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日" + "hh:mm:ss");
		String time = sdf.format(new Date());
		MyDatabaseUtil.getInstance(context).insertDataMSG(title, content, time);
	}

	// 插入 友盟消息推送数据 xiabing
	private void insertDataMSG(String title, String content, String time) {
		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		String type = null;
		if (title.equals(contexts.getString(R.string.pushtitle))) {
			type = "1";
		} else {
			type = "2";
		}

		mockYouMengNews(title, content, time, type).save();

		// db.execSQL("insert into " + DB_TABLE1
		// + "(title,content,time,type) values(?,?,?,?)", new String[] {
		// title, content, time, type });
		// db.close();
		if (notifyListener == null) {
			Log.d("xiabing", "otifyListener==null");
		}
		if (notifyListener != null) {
			Log.d("xiabing", "otifyListener!=null");
			notifyListener.nofityMessageListShow();
		}
	}

	private static YouMengNews mockYouMengNews(String title, String content,
			String time, String type) {
		YouMengNews youMengNews = new YouMengNews();
		youMengNews.content = content;
		youMengNews.title = title;
		youMengNews.time = time;
		youMengNews.type = type;
		return youMengNews;
	}

	public static void insertDefaultMSG() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日" + "hh:mm:ss");
		String time = sdf.format(new Date());
		String title = "应用介绍";
		String[] content = new String[3];
		content[0] = "你好，欢迎使用ibeacon智能考勤系统！";
		content[1] = "你好，欢迎使用ibeacon智能考勤系统！";
		content[2] = "你好，欢迎使用ibeacon智能考勤系统！";

		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		for (int i = 0; i < content.length; i++) {
			// db.execSQL("insert into " + DB_TABLE1
			// + "(title,content,time,type) values(?,?,?,?)",
			// new String[] { title, content[i], time, "1" });
			mockYouMengNews(title, content[i], time, "1").save();
		}
		// db.close();
	}

	// 查询 友盟消息推送数据 xiabing
	public static List<Map<String, Object>> queryDatafornews() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		// Cursor cursor = db.rawQuery("select * from " + DB_TABLE1
		// + " ORDER BY time desc", null);
		List<YouMengNews> result = new Select().from(YouMengNews.class)
				.orderBy("time desc").execute();
		for (int i = 0; i < result.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", result.get(i).getId());
			map.put("title", result.get(i).title);
			map.put("content", result.get(i).content);
			map.put("time", result.get(i).time);
			map.put("type", result.get(i).type);
			list.add(map);
		}
		// db.close();
		// cursor.close();
		return list;
	}

	public static void deletePushData(String _id) {
		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		// db.execSQL("delete from " + DB_TABLE1 + " where _id=?",
		// new String[] { _id });
		// db.close();
		new Delete().from(YouMengNews.class).where("id=?", _id).execute();
	}

	private static void insertDateTimeExtra(Context context, Date now) {
		SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy年MM月dd日",
				Locale.CHINA);
		SimpleDateFormat timeformatter = new SimpleDateFormat("HH:mm:ss",
				Locale.CHINA);

		// DateFormat dateFormat = DateFormat.getDateInstance();
		// String date = dateFormat.format(now);
		// DateFormat dateFormat2 = DateFormat.getTimeInstance();
		// String time = dateFormat2.format(now);
		String date = dateformatter.format(now);
		String time = timeformatter.format(now);

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		String detail = dateFormat.format(now);

		MyDatabaseUtil.getInstance(context).insertData(date, time, detail);
		// add signin data for bmob begin
		SignInData mSignInDate = new SignInData();
		if (!SharedPreferenceUtil.accountIsEmpty(context)) {
			String account = SharedPreferenceUtil.getAccount(context);
			String name = SharedPreferenceUtil.getName(context);
			mSignInDate.setAccount(account);
			mSignInDate.setName(name);
			mSignInDate.setTime(detail);
			mSignInDate.save(context, new SaveListener() {

				@Override
				public void onSuccess() {
					// TODO Auto-generated method stub
					Log.d(TAG, "mSignInDate save onSuccess");
				}

				@Override
				public void onFailure(int arg0, String arg1) {
					// TODO Auto-generated method stub
					Log.d(TAG, "mSignInDate save onFailure arg1:" + arg1);
				}
			});
		}
		// add signin data for bmob end
	}

	public static void DatabaseInit(Context context) {
		// if (databaseHelper == null)
		// databaseHelper = new MyDatabaseHelper(context, DB_NAME, null, 1);
		if (myDatabaseUtil == null) {
			myDatabaseUtil = new MyDatabaseUtil();
		}
	}

	public static MyDatabaseUtil getInstance(Context context) {
		contexts = context;
		if (myDatabaseUtil == null) {
			DatabaseInit(context);
		}
		return myDatabaseUtil;
	}

	private void notifyListeners() {
		if (dataListeners != null && dataListeners.size() != 0) {
			for (int i = 0; i < dataListeners.size(); i++) {
				dataListeners.get(i).notifyDataUpdate();
			}
		}
	}

	public void updateData(String date, String time, String id) {
		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		// db.execSQL("update " + DB_TABLE
		// + " set date=? and set time=? where id=?", new String[] { date,
		// time, id });
		// db.close();
		new Update(ShuaKaData.class).set("date=? and time=?", date, time)
				.where("id=?", id).execute();
	}

	private ShuaKaData mockShuaKaData(String date, String time, String detail) {
		ShuaKaData shuaKaData = new ShuaKaData();
		shuaKaData.date = date;
		shuaKaData.time = time;
		shuaKaData.detail = detail;
		return shuaKaData;
	}

	public void insertData(String date, String time, String detail) {
		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		// db.execSQL("insert into " + DB_TABLE
		// + "(date,time,detail) values(?,?,?)", new String[] { date,
		// time, detail });
		// db.close();
		mockShuaKaData(date, time, detail).save();
		notifyListeners();
	}

	public void deleteData(String date) {
		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		// db.execSQL("delete from " + DB_TABLE + " where date=?",
		// new String[] { date });
		// db.close();
		new Delete().from(ShuaKaData.class).where("date=?", date).execute();
	}

	public List<Map<String, Object>> queryData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		// Cursor cursor = db.rawQuery("select * from " + DB_TABLE
		// + " ORDER BY date desc, time desc", null);
		List<ShuaKaData> result = new Select().from(ShuaKaData.class)
				.orderBy("date desc, time desc").execute();
		for (int i = 0; i < result.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("date", result.get(i).date);
			map.put("time", result.get(i).time);
			list.add(map);
		}
		// db.close();
		// cursor.close();
		return list;
	}

	public List<List<Map<String, Object>>> queryDataList() {
		List<List<Map<String, Object>>> list = new ArrayList<List<Map<String, Object>>>();

		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		// Cursor cursor = db.rawQuery("select * from " + DB_TABLE
		// + " ORDER BY date desc", null);// , time desc
		List<ShuaKaData> result = new Select().from(ShuaKaData.class)
				.orderBy("date desc").execute();

		String oldString = null;
		List<Map<String, Object>> list2 = null;
		for (int i = 0; i < result.size(); i++) {
			String dateString = result.get(i).date;// cursor.getString(1);
			String timeString = result.get(i).time;// cursor.getString(2);

			if (oldString == null && list2 == null) {
				list2 = new ArrayList<Map<String, Object>>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("date", dateString);
				map.put("time", timeString);
				list2.add(map);
			} else if (oldString != null && !oldString.equals(dateString)
					&& list2 != null) {
				list.add(list2);
				list2 = new ArrayList<Map<String, Object>>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("date", dateString);
				map.put("time", timeString);
				list2.add(map);
			} else if (oldString != null && oldString.equals(dateString)
					&& list2 != null) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("date", dateString);
				map.put("time", timeString);
				list2.add(map);
			}
			oldString = dateString;
		}
		if (list2 != null)
			list.add(list2);
		// db.close();
		// cursor.close();
		return list;
	}

	public String[] queryTodayFirstLastTime() {// 获取当天第一次和最后一次刷卡时间
		Date now = new Date();
		SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy年MM月dd日",
				Locale.CHINA);
		String date = dateformatter.format(now);

		// SQLiteDatabase db = databaseHelper.getReadableDatabase();
		// Cursor cursor = db.rawQuery("select * from " + DB_TABLE
		// + " where date like ?" + " ORDER BY time",
		// new String[] { date });
		String[] firstLastStrArr = new String[2];
		// if (cursor.moveToNext()) {
		// firstLastStrArr[0] = firstLastStrArr[1] = cursor.getString(3);
		// while (cursor.moveToNext()) {
		// firstLastStrArr[1] = cursor.getString(3);
		// }
		// }
		// cursor.close();
		// db.close();
		List<ShuaKaData> result = new Select().from(ShuaKaData.class)
				.where("date like ?", date).orderBy("time desc").execute();
		if (result.size() > 0) {
			firstLastStrArr[0] = firstLastStrArr[1] = result.get(0).time;
			firstLastStrArr[1] = result.get(result.size() - 1).time;
		}
		return firstLastStrArr;
	}

	public String[] queryTodayFirstLastTime(String date) {// 获取指定日期第一次和最后一次刷卡时间
	// SQLiteDatabase db = databaseHelper.getReadableDatabase();
	// Cursor cursor = db.rawQuery("select * from " + DB_TABLE
	// + " where date like ?" + " ORDER BY time",
	// new String[] { date });
		String[] firstLastStrArr = new String[2];
		// if (cursor.moveToNext()) {
		// firstLastStrArr[0] = firstLastStrArr[1] = cursor.getString(3);
		// while (cursor.moveToNext()) {
		// firstLastStrArr[1] = cursor.getString(3);
		// }
		// }
		// cursor.close();
		// db.close();
		List<ShuaKaData> result = new Select().from(ShuaKaData.class)
				.where("date like ?", date).orderBy("time desc").execute();
		if (result.size() > 0) {
			firstLastStrArr[0] = firstLastStrArr[1] = result.get(0).time;
			firstLastStrArr[1] = result.get(result.size() - 1).time;
		}
		return firstLastStrArr;
	}

	// private static class MyDatabaseHelper extends SQLiteOpenHelper {
	//
	// public MyDatabaseHelper(Context context, String name,
	// CursorFactory factory, int version) {
	// super(context, name, factory, version);
	// }
	//
	// @Override
	// public void onCreate(SQLiteDatabase db) {
	// db.execSQL(DB_CREATE);
	// db.execSQL(DB_CREATE2);
	// }
	//
	// @Override
	// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	// {
	// db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
	// onCreate(db);
	// }
	// }
}
